package com.sky.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.internal.util.file.IOUtils;
import com.sky.his.api.common.MinioUtil;
import com.sky.his.api.common.PageUtils;
import com.sky.his.api.common.R;
import com.sky.his.api.exception.HisException;
import com.sky.his.api.mis.controller.form.AddCheckupDayBillForm;
import com.sky.his.api.mis.controller.form.CreateCheckupReportForm;
import com.sky.his.api.mis.controller.form.SearchCheckupReportByPageForm;
import com.sky.his.api.mis.service.CheckupReportService;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mis/checkup/report")
public class CheckupReportController {

    @Resource
    private CheckupReportService checkupReportService;
    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/searchByPage")
    @SaCheckPermission(value = {"REPORT:SELECT", "ROOT"}, mode = SaMode.OR)
    public R searchByPage(@RequestBody @Valid SearchCheckupReportByPageForm form) {
        // 获取页面和每页数据条数
        int page = form.getPage();
        int length = form.getLength();

        // 计算查询起始位置
        int start = (page - 1) * length;

        // 将表单数据转换为 HashMap 并添加分页参数
        HashMap<String, Object> param = JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start", start);

        // 调用服务层方法进行分页查询
        PageUtils pageUtils = checkupReportService.searchByPage(param);

        // 返回成功的响应，携带分页数据
        return R.ok().put("page", pageUtils);
    }

    @PostMapping("/createReport")
    @SaCheckPermission(value = {"ROOT", "CHECKUP_REPORT:SELECT"}, mode = SaMode.OR)
    public R createReport(@RequestBody @Valid CreateCheckupReportForm form) {
        boolean bool = checkupReportService.createReport(form.getId());
        return R.ok().put("result", bool);
    }

    @GetMapping("/downloadReport")
    @SaCheckPermission(value = {"ROOT", "CHECKUP_REPORT:SELECT"}, mode = SaMode.OR)
    public void downloadReport(@RequestParam String filePath, @RequestParam String name,
                               HttpServletResponse response) {
        if (StrUtil.isBlank(name)) {
            throw new HisException("name不能为空");
        } else if (!ReUtil.isMatch("^[\\u4e00-\\u9fa5]{2,10}$", name)) {
            throw new HisException("name内容不正确");
        }
        try (InputStream in = minioUtil.downloadFile(filePath);
             OutputStream out = response.getOutputStream()) {

            response.reset();
            response.setContentType("application/x-msdownload;charset=UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(name + "的体检报告.docx", "UTF-8") + "\"");

            IOUtils.copy(in, out);

        } catch (Exception e) {
            throw new HisException("下载体检报告失败", e); // Added the exception for better traceability
        }
    }

    @SneakyThrows
    @PostMapping("/identifyWaybill")
    @SaCheckPermission(value = {"ROOT", "CHECKUP_REPORT:UPDATE"}, mode = SaMode.OR)
    public R identifyWaybill(@RequestParam("file") MultipartFile file) {
        InputStream in = file.getInputStream();
        BufferedImage image = ImgUtil.read(in);
        String imgBase64 = "data:image/jpg;base64," + ImgUtil.toBase64(image, "jpg");
        in.close();
        HashMap map = checkupReportService.identifyWaybill(imgBase64);
        return R.ok().put("result", map);
    }

    @PostMapping("/addWaybill")
    @SaCheckPermission(value = {"ROOT", "public"})
    public R addWaybill(@RequestBody @Valid AddCheckupDayBillForm form) {
        Map<String, Object> param = BeanUtil.beanToMap(form);

        param.put("status", 3);

        boolean result = checkupReportService.addWayBill(param);

        return R.ok().put("result", result);
    }

    @PostMapping("/importWaybills")
    @SaCheckPermission(value = {"ROOT", "CHECKUP REPORT:UPDATE"}, mode = SaMode.OR)
    public R importWaybills(@RequestParam("file") MultipartFile file) throws IOException {
        // 调用服务方法进行导入
        XSSFWorkbook workbook = checkupReportService.importWayBill(file);  // 假设你的服务方法返回一个 XSSFWorkbook 对象
        if (workbook != null) {
            // 创建字节流输出
            ByteArrayOutputStream out = new ByteArrayOutputStream();  // 修正了语法
            workbook.write(out);
            workbook.close();  // 关闭 workbook 流

            // 转换为字节数组并编码为 base64 字符串
            byte[] byteArray = out.toByteArray();
            String base64 = Base64.encode(byteArray);

            // 返回成功响应
            return R.ok().put("fileBase64", base64);
        }

        // 返回空响应
        return R.ok();
    }

}
